package dgut.party.business.api;

import dgut.party.business.common.util.FileService;
import dgut.party.business.common.util.JsonResult;
import dgut.party.business.security.UserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
public class IOController {

  @Autowired
  FileService fileService;

  @RequestMapping("/img/{type}/{id}")
  public ResponseEntity<byte[]> imgRetrieve(@PathVariable(name = "type") String type,
                                            @PathVariable(name = "id") String id) throws IOException {
    String filePath = fileService.getUploadRoot() + "/" + type + "/" + id;
    try {
      return fileService.downloadFile(filePath);
    } catch (Exception e) {
      if (type.equals("brand")) {
        return fileService.downloadFile(fileService.getUploadRoot() + "/" + type + "/default");
      }
      return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
  }

  @RequestMapping(value = "/img/upload/headimg")
  public Object uploadMyheadImg(Authentication auth, MultipartFile file) throws IOException {
    Long userId = ((UserPrincipal) auth.getPrincipal()).getId();
    String fileName = fileService.uploadFile(fileService.getUploadRoot() + "/" + userId + "/headimg/", file);
    return JsonResult.successJsonResultMap(fileName);
  }
}
